#include"my_stdio.h"
MY_FILE* my_fopen(const char* path,const char* mode)
{
    assert(path);
    int flag=0;
    if(strcmp(mode,"r")==0)
    {
       flag|=O_RDONLY;
    }
    else if(strcmp(mode,"w")==0)
    {
       flag|=O_CREAT|O_TRUNC|O_WRONLY;
    }
    else if(strcmp(mode,"a")==0)
    {
      flag|=O_CREAT|O_WRONLY|O_APPEND;
    }
    else{

    }
    mode_t m=0666;
    int fd=0;//文件描述符
    if(flag&O_CREAT)
    {
      fd=open("path",flag,m);
    }
    else{
      fd=open("path",flag);
    }
   MY_FILE* my_file=(MY_FILE*)malloc(sizeof(MY_FILE));
   assert(my_file);
   my_file->_fd=fd;
   my_file->flag=ROW_BUF;
   memset(my_file->buf,'\0',1024);
  my_file->countCurrent=0;
  return my_file;
}
  size_t my_fwrite(const char* ptr,size_t size,size_t nmemb,MY_FILE* stream)
{
  if(stream->countCurrent==1024)
  {
    my_fflush(stream);
  }
  size_t user_num=size*nmemb;
  size_t capacity=1024-stream->countCurrent;
  size_t writen=0;
  if(user_num<capacity)
  {
    strcpy(stream->buf+stream->countCurrent,ptr);
    stream->countCurrent=stream->countCurrent+user_num;
    writen=stream->countCurrent;
    if(*(ptr+sizeof(ptr)-1)=='\n')
    {
      my_fflush(stream);    
    }
  }
  else if(user_num>=capacity)
  {
    strncpy(stream->buf+stream->countCurrent,ptr,1024);
    my_fflush(stream);
    writen=1024;
  }

  return writen;
}
int my_fflush(MY_FILE* fp)
{
  assert(fp);
  write(fp->_fd,fp->buf,fp->countCurrent);
  fp->countCurrent=0;
  fsync(fp->_fd);
  return 0;
}
int my_fclose(MY_FILE *fp)
{
  assert(fp);
  my_fflush(fp);
  close(fp->_fd);
  free(fp);
  fp=NULL;
  return 0;}

